require(['./config'],()=>{
    require(['template','url','header','footer','fly'],(template,url,header)=>{
        class Detail{
            constructor(){     
              
              this.getData().then(()=>{
                  this.render()
                  this.tab() 
                  this.bindEvents()
                  this.addToCart()
                  
              })
            }
            getData(){
              //从地址栏拿数据
              const id = window.location.search.slice(1).split('&').reduce((obj,item)=>{
                         var arr = item.split('=')
                         obj[arr[0]] = arr[1]
                         return obj
              },{}).id
              this.id = Number(id)  
              //利用ajax发送请求
              return new Promise(resolve =>{
                $.get(`${url.rap2}/api/detail`,{id:this.id},resp=>{
                  console.log(resp)
                   //处理返回的数据
                   if(resp.code === 200){
                       const {detail} = resp.body
                       //前端处理id问题
                       this.detail = { ...detail , id:this.id}
                       resolve()
                   }
                })
              })
             
            }
            render(){
            $('#goodsImg').html(template('templateDetail',{
                  ...this.detail
            }))
            }
          //放大镜
          bindEvents(){
            $('.bigImg').hover(()=>{
              $('.bigImg span').show()
              $('.bigBox').show()
          },()=>{
            $('.bigImg span').hide()
              $('.bigBox').hide()
          })
          $('.bigImg').on('mousemove',e =>{
              var top = e.pageY- $('.bigImg').offset().top
              var left = e.pageX- $('.bigImg').offset().left

              //鼠标位置
              left -= $('.bigImg span').outerWidth()/2
              top -= $('.bigImg span').outerHeight()/2
              this.move(left,top)
          })
         
          }
          move(left,top){
          //限定范围
          if(left<0) left=0
          if(top<0) top=0
          if(left>$('.bigImg').innerWidth() - $('.bigImg span').outerWidth())
          left = $('.bigImg').innerWidth()- $('.bigImg span').outerWidth()
          if(top> $('.bigImg').innerHeight() -$('.bigImg span').outerHeight())
          top= $('.bigImg').innerHeight() - $('.bigImg span').outerHeight()       
          $('.bigImg span').css({left,top})       
          $('.bigBox img').css({
              left: -2*left,
              top:-2*top
          })   
          }
          tab(){
          $('#gall li img').on('click',function(){
            $('.bigImg img').attr('src',$(this).attr('src'))
            $('.bigBox img').attr('src',$(this).attr('src'))
          })
          }  
          addToCart(){
            $('#add-to-cart').on('click',e=>{
              this.fly(e)
              let cart = localStorage.getItem('cart')
              var count = Number($('.add-num1').val())     
              if (cart) {
                  // 有数据
                  cart = JSON.parse(cart)
                  //购物车有数据,进行进一步判断（当前商品在购物车是否存在：some）
                  const isExist = cart.some(shop => {
                      return shop.id === this.detail.id
                  })
                  if (isExist) {
                      cart = cart.map(shop => {
                          if (shop.id === this.detail.id) {
                              shop.count++
                          }
                          return shop
                      })
                  } else {
                   //购物车为空，直接push
                      cart.push({
                          ...this.detail, count:1 , checked:true 
                      })
                  }
                  // 重新再存一次
                  localStorage.setItem('cart', JSON.stringify(cart))
              } else {
                  // 购物车为空
                  localStorage.setItem('cart', JSON.stringify([ {//用数组存储
                      ...this.detail,  count:1 , checked:true  //默认选中
                  } ]))
              }
            })
          }
          fly(e){
             $(`<img src="${this.detail.imgs[0]}" style="width: 50px;height: 50px;border-radius:50%">`).fly({
              start:{
                left:e.clientX,
                top:e.clientY,
              },
              end:{
                left:$('.carts').offset().left - $(window).scrollLeft(),
                top:$('.carts').offset().top - $(window).scrollTop()
              },
              speed:1.1,
              vertex_Rtop:100,//最高点
              onEnd:function(){
                this.destroy()
                header.calcCartTotal()
              }
             })
 
            }
          
      }
        new Detail()
    })
})